package contegor.scire.core;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

/**
 * Implementación genérica de un mensaje.
 *
 * @version $Revision: 1.1 $
 * @author  Héctor Cirbián Pousa ($Author: hector $)
 */
@Version("$Id: MessageImpl.java,v 1.1 2009-10-12 21:13:44 hector Exp $")
@Deprecated
public class MessageImpl<R> implements Message<R> {
  private static final long serialVersionUID = 5650050869586915054L;

  protected Task<R>       firstTask;
  protected List<Task<R>> tasks;

  public MessageImpl() {
    this.firstTask = null;
    this.tasks     = null;
  }

  public MessageImpl(Task<R> task) {
    this.firstTask = task;
    this.tasks     = null;
  }

  public void addTask(Task<R> task) {
    if (firstTask == null)
      firstTask = task;
    else {
      if (tasks == null) {
        tasks = new ArrayList<Task<R>>();
        tasks.add(firstTask);
      }
      if ((task.getTargetContainerId() != Id.EMPTY) &&
          (!firstTask.getTargetContainerId().equals(task.getTargetContainerId())))
        throw new IllegalArgumentException("Adding Tasks with different target Container to the same Message.");
      else
        tasks.add(task);
    }
  }

  public Id getTargetContainerId() {
    if (firstTask == null)
      return null;
    return firstTask.getTargetContainerId();
  }

  public Iterator<Task<R>> iterator() {
    if (tasks == null) {
      return new Iterator<Task<R>>() {
        private boolean next = true;

        public boolean hasNext() {
          return next;
        }

        public Task<R> next() {
          if (next) {
            next = false;
            return firstTask;
          }
          else
            throw new NoSuchElementException();
        }

        public void remove() {
          throw new UnsupportedOperationException();
        }
      };
    }
    else
      return tasks.iterator();
  }
}
